<?php

namespace app\service\admin\projects\music;

use app\model\Common;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

class SongService
{

    /**
     * 列表数据
     * @param array $request
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function getList(array $request): array
    {
        $page = $request['page'] ?? 1;
        $size = $request['size'] ?? 10;
        $so = $request['so'] ?? '';
        $filter = [];
        if ($so) {
            $filter[] = [function ($query) use ($so) {
                $query->where('title', 'like', $so . '%')
                    ->whereOr('author', 'like', $so . '%');
            }];
        }
        $field = ['id', 'title', 'author', 'pic', 'url', 'status', 'file_name', 'create_time'];
        $res = Common::getList(MusicTable, $filter, $field, $page, $size);
        if ($res) {
            foreach ($res['data'] as &$v) {
                $v['pic'] = imagePath($v['pic']);
            }
        }
        return $res;
    }

    /**
     * 添加
     * @param array $request
     * @return int|string
     */
    public static function add(array $request)
    {
        $path = imagePath($request['url']);
        $request['hash'] = hash('sha256', $path['src']);  //文件唯一hash值
        return Common::addData(MusicTable, $request);
    }

    /**
     * 修改
     * @param array $request
     * @return int
     * @throws DbException
     */
    public static function update(array $request): int
    {
        return Common::updateData(MusicTable, ['id' => $request['id']], $request);
    }

    /**
     * 删除
     * @param array $request
     * @return false|int|string
     * @throws DbException
     */
    public static function delete(array $request)
    {
        $ids = [];
        if (!isset($request['data']) || !$request['data']) {
            return false;
        }
        foreach ($request['data'] as $v) {
            $ids[] = $v['id'];
        }
        return Common::deleteData(MusicTable, ['id' => $ids]);
    }
}